package com.yanfan.energy.service;


import com.yanfan.energy.domain.statist.DateStatistics;
import com.yanfan.energy.mapper.EnergyPriceSettingDao;
import com.yanfan.energy.mapper.PurchasingEnergysDao;
import com.yanfan.energy.util.DateUtils;
import com.yanfan.energy.util.DoubleOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @Author huan
 * @Description 价格缓存相关
 * @ClassName 2022年12月02日 10:26:00
 * @Version 1.0
 **/
@Component
public class EnergyPriceCache {

    @Autowired
    EnergyPriceSettingDao energyPriceSettingDao;

    @Autowired
    PurchasingEnergysDao purchasingEnergysDao;

    /**
     * 获取setting表里面的价格
     *
     * @return
     * @throws Exception
     */
    @Cacheable("settingPrice")
    public Map<Integer, Double> energyPriceMapCaChe() throws Exception {
        List<DateStatistics> energyPriceSettings = energyPriceSettingDao.findPriceByType();
        if (CollectionUtils.isEmpty(energyPriceSettings)) {
            throw new Exception("能源单价表为空！ energy_price_setting");
        }
        Map<Integer, Double> respMap = new HashMap<>();
        energyPriceSettings.forEach(energyPriceSetting -> {
            respMap.put(Math.toIntExact(energyPriceSetting.getCount()), energyPriceSetting.getNumber());
        });
        return respMap;
    }

    @Cacheable(value = "findNaturalByEndDate", key = "#endDate")
    public Double findNaturalByEndDate(String endDate) throws ParseException {
        // 计算某个月份的总费用
        List<DateStatistics> naturalByEndDate = purchasingEnergysDao.findNaturalByEndDate(endDate);
        if (CollectionUtils.isEmpty(naturalByEndDate)) {
//            throw  new Exception("燃气费用单价为空！ purchasing_energy");

            return 0.0;
        }
        //月份的总费用
        Double number = naturalByEndDate.get(0).getNumber();

        String beginDate = endDate + "-01";
        List<Double> dosageList = purchasingEnergysDao.findNaturalDosageByEndDate(beginDate, DateUtils.nextMonthFirstDate(beginDate));
        if (CollectionUtils.isEmpty(dosageList)) {
            return 0.0;
        }
        AtomicReference<Double> energyConsumption = new AtomicReference<>(0.0);
        dosageList.forEach(dosage -> {
            energyConsumption.set(DoubleOperation.addNonNullTrack(energyConsumption.get(), dosage));
        });
        if (number == 0.0 || energyConsumption.get() == 0.0) {
            return 0.0;
        }
        return DoubleOperation.divide(number, energyConsumption.get());
    }


}
